<template>
  <common-list-group class="report-component-wrap">
    <div slot="group">
      <div class="group-header-wrap">
        <div class="group-header-title">规则类型</div>
      </div>
      <common-tree
        ref="treeRef"
        :isRequest="isRequest"
        :treeLoading="treeLoading"
        :is-slot="true"
        :tree-data="groupTreeData"
        search-placeholder="查询分类"
        :current-node-key="currentNodeKey"
        @handleNodeClick="handleNodeClick"
      >
        <div slot-scope="{ scope }" class="tree-item-wrap">
          <common-carousel-text :content="scope.data.name" :font-size="14" />

          <!-- <el-popover
            v-if="scope.data.isDefault === 0"
            popper-class="chart-type-list-popover"
            placement="right-start"
            width="150"
            trigger="hover"
          >
            <i slot="reference" class="iconfont icon-more"></i>
            <common-menu>
              <common-menu-item
                v-if="scope.data.isEnableAdd"
                @click="treeAdd(scope.data)"
                >新增分类
              </common-menu-item>
              <common-menu-item
                v-if="!scope.data.isRoot"
                @click="treeEdit(scope.data)"
                >编辑
              </common-menu-item>
              <common-menu-item
                v-if="!scope.data.isRoot"
                @click="treeDelete(scope.data)"
                >删除</common-menu-item
              >
            </common-menu>
          </el-popover> -->
        </div>
      </common-tree>
    </div>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        v-model="query"
        ref="queryForm"
        :inline="true"
        label-width="65px"
      >
        <el-form-item label="规则类别" prop="ruleType">
          <el-select v-model="query.ruleType" filterable style="width: 100%">
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in ruleTypeList"
              :key="item.paramValue"
              :label="item.paramName"
              :value="item.paramValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="规则编码" prop="ruleCode">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="query.ruleCode"
          />
        </el-form-item>
        <el-form-item label="规则名称" prop="ruleName">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="query.ruleName"
          />
        </el-form-item>
        <el-form-item label="告警码" prop="alarmCode">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="query.alarmCode"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="query.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="启用" :value="0"></el-option>
            <el-option label="停用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>

    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['datascan:alertrule:add']"
          v-if="custom"
          type="primary"
          icon="el-icon-plus"
          @click="add"
          plain
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['datascan:alertrule:import']"
          v-if="custom"
          type="primary"
          plain
          icon="el-icon-download"
          @click="importShow"
          >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['datascan:alertrule:export']"
          type="primary"
          :disabled="ruleList < 1"
          plain
          icon="el-icon-upload2"
          :loading="exportLoading"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['datascan:alertrule:remove']"
          v-if="custom"
          :disabled="ids.length < 1"
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleDelete"
          >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-circle-check"
          :disabled="ids.length < 1"
          @click="handleChangeStatus(0)"
          v-hasPermi="['datascan:alertrule:edit']"
          >启用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-remove-outline"
          :disabled="ids.length < 1"
          @click="handleChangeStatus(1)"
          v-hasPermi="['datascan:alertrule:edit']"
          >停用
        </el-button>
      </el-col>
    </el-row>

    <!--列表 start-->
    <common-table
      v-loading="isLoading"
      slot="content"
      :data="ruleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="规则类别"
        align="left"
        prop="ruleType"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ getRuleTypeCN(scope.row.ruleType) }}
        </template>
      </el-table-column>
      <el-table-column
        label="规则编码"
        align="left"
        prop="ruleCode"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="规则名称"
        align="left"
        prop="ruleName"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="告警码"
        align="left"
        width="120"
        prop="alarmCode"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="规则条件"
        align="left"
        prop="ruleDetails"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ getRuleCondition(scope.row.ruleDetails) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status" width="90">
        <template slot-scope="scope">
          <!-- {{ scope.row.status | ruleStatusFilter }} -->
          <!-- 0 启用  1停用 -->
          <el-tag type="success" v-if="scope.row.status == 0">启用</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 1">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="160">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['datascan:alertrule:edit']"
            type="text"
            @click="handleShake(scope.row)"
            :disabled="scope.row.isDisabledForShake"
          >
            <span v-if="scope.row.status == 1">启用</span>
            <span v-if="scope.row.status == 0">停用</span>
          </el-button>
          <el-button type="text" @click="handleView(scope.row)">
            详情
          </el-button>
          <el-button
            v-hasPermi="['datascan:alertrule:edit']"
            type="text"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>

          <el-button
            v-hasPermi="['datascan:alertrule:remove']"
            type="text"
            v-if="scope.row.isDefault === 0"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />
    <common-upload-dialog
      download-path="system/downFileByemplateName"
      upload-path="/datahandler/alertrule/importAlertRule"
      template-name="ruleTemplate.xlsx"
      report-path="system/downErrorReportByemplateName"
      acceptType=".txt"
      ref="uploadDialog"
      :getList="getList"
    />
    <rule-add
      v-if="isShowAddRule"
      ref="ruleAdd"
      :isEdit="isEdit"
      :editForm="editForm"
      :currentNodeKey="currentNodeKey"
      :typeStaticOption="optionList"
      :typeStaticListOption="optionListField"
      @close="closeAdd"
    ></rule-add>

    <rule-type-dialog
      ref="ruleTypeDialog"
      :isTypeEdit="isTypeEdit"
      @toQueryAllTree="getTreeList"
    />

    <rule-detail
      ref="ruleDetail"
      :typeStaticOption="optionList"
      :typeStaticListOption="optionListField"
    />
  </common-list-group>
</template>

<script>
import { getRuleCondition } from "@/utils/util";
import { getColumnList } from "@/api/datascan/alarmRules/rules";
import RuleAdd from "./components/RuleAdd/index";
import RuleTypeDialog from "./components/RuleTypeDialog.vue";
import RuleDetail from "./components/RuleDetail.vue";

import {
  listType,
  fetchTreeList,
  typeTreeAdd,
  typeTreeEdit,
  typeTreeDelete,
  fetchRuleList,
  ruleDetail,
  ruleAdd,
  ruleEdit,
  ruleStatusBatchEdit,
  ruleDelete,
  fetchOptions,
  fetchMergeField,
} from "@/api/datascan/alarmRules/rules";
import { alarmCodeGetAlarmLevel } from "@/api/system/alarmCode";
import BaseList from "@/mixins/BaseList";

export default {
  name: "index",
  mixins: [BaseList],
  components: {
    RuleAdd,
    RuleTypeDialog,
    RuleDetail,
  },
  data() {
    return {
      exportLoading: false,
      isRequest: false,
      treeLoading: false,
      treeList: [],
      isLoading: false,
      isEdit: false,
      ids: [],
      total: 0,
      assetId: null,
      single: true,
      multiple: true,
      ruleList: [],
      query: {
        pageNum: 1,
        pageSize: 10,
        ruleCode: null,
        ruleName: null,
        ruleType: null,
        status: null,
      },
      groupTreeData: [],
      groupTreeProp: {},
      currentNodeKey: "0",
      treeIds: [],
      getParentNodeData: [],
      isShowAddRule: false,
      isTypeEdit: false,
      custom: false,
      selectionRows: [],
      editForm: {},
      currentCustomId: "",
      ruleTypeList: [],
      optionList: [],
      optionListField: [],
    };
  },
  mounted() {
    // this.getList();
    this.getColumnList();
    this.getTreeList();
    this.getOptions(1); //告警规则类别
    // this.getOptions(2); //告警等级
    this.getAlarmLevel(); //告警等级
    this.getOptions(3); //规则类型
    this.getOptions(4); //杀伤链
    this.getOptions(5); //索引类型
    this.getOptions(6); //字段类型对应的操作符
    this.getOptions(7); //对比字段下拉框
    this.getOptions(8); //条件1、条件2

    this.getFieldList();
  },
  methods: {
    getColumnList() {
      getColumnList({ indexId: "1328296158756474880" }).then((res) => {
        if (res && res.code === 200) {
          this.optionList = res.data;
        } else {
          this.optionList = [];
        }
      });
    },
    getAlarmLevel() {
      alarmCodeGetAlarmLevel().then((res) => {
        this.$store.commit("rule/SET_ALARM_LEVEL_LIST", res.data || []);
      });
    },
    getRuleCondition(ruleDetails) {
      return getRuleCondition(ruleDetails);
    },

    getFieldList() {
      fetchMergeField({ indexId: "1406666658846097674" }).then((res) => {
        if (res && res.code === 200) {
          this.optionListField = res.data;

          // //告警合并字段
          // let staticData = res.data.filter((item) => item.isStatistics === 0);
          // //关联字段/时序字段值/不同维度/规则查询条件
          // let searchData = res.data.filter((item) => item.isSearch === 0);
          // //指标字段/对比字段
          // let showData = res.data.filter((item) => item.isShow === 0);

          // //指标字段
          // let showLessData = res.data.filter(
          //   (item) =>
          //     item.isShow === 0 &&
          //     (item.columnType === "Integer" ||
          //       item.columnType === "Double" ||
          //       item.columnType === "Long")
          // );

          // this.$store.commit("rule/SET_TYPE_STATIC_LIST", staticData || []);
          // this.$store.commit("rule/SET_TYPE_SEARCH_LIST", searchData || []);
          // this.$store.commit("rule/SET_TYPE_SHOW_LIST", showData || []);
          // this.$store.commit(
          //   "rule/SET_TYPE_SHOW_LESS_LIST",
          //   showLessData || []
          // );
        }
      });
    },

    getOptions(option) {
      fetchOptions({ paramType: option }).then((res) => {
        if (res && res.code === 200) {
          if (option === 1) {
            //告警规则类别
            this.ruleTypeList = res.data || [];
            this.$store.commit("rule/SET_RULE_TYPES", res.data || []);
          }
          // if (option === 2) {
          //   //告警等级
          //   this.$store.commit("rule/SET_DEGREE_LIST", res.data || []);
          // }
          if (option === 3) {
            //规则类型
            this.$store.commit("rule/SET_ALERT_TYPE_LIST", res.data || []);
          }
          if (option === 4) {
            //杀伤链
            this.$store.commit("rule/SET_KILL_CHAIN_LIST", res.data || []);
          }
          if (option === 5) {
            //索引类型
            this.$store.commit("rule/SET_INDEX_TYPES_LIST", res.data || []);
          }
          if (option === 6) {
            //过滤规则 标点符号
            this.$store.commit("log/SET_OPERATOR_LIST", res.data || []);
          }
          if (option === 8) {
            //条件1、条件2 标点符号
            this.$store.commit("rule/SET_CONDITION_OPER_LIST", res.data || []);
          }
        }
      });
    },

    getRuleTypeCN(val) {
      return this.ruleTypeList.find((item) => item.paramValue === val)
        ?.paramName;
    },
    treeAdd(row) {
      //树节点新增
      this.$refs.ruleTypeDialog.show(null);
      this.isTypeEdit = false;
    },
    treeEdit(row) {
      //树节点重命名
      this.$refs.ruleTypeDialog.show(row);
      this.isTypeEdit = true;
      console.log(row);
    },
    treeDelete(row) {
      // 树节点删除
      this.$GlobalDeleteConfirm()
        .then(() => {
          typeTreeDelete({ ids: row.id })
            .then((res) => {
              this.$GlobalSuccessMessage("删除成功");
              this.getTreeList();
            })
            .finally(() => {});
        })
        .catch(() => {});
    },

    handleNodeClick(info) {
      this.currentNodeKey = info.data.id;
      this.custom = info.data.isDefault === 0;
      this.query.pageNum = 1;
      this.query.pageSize = 10;
      this.query.isDefault = info.data.isDefault;

      this.getList();
    },
    getTreeList() {
      // 树节点列表
      this.treeLoading = true;
      fetchTreeList({ id: null })
        .then((res) => {
          if (res && res.code === 200) {
            this.groupTreeData = [
              {
                name: "规则类型",
                id: "0",
                children: [
                  {
                    name: "预定义", // 名称
                    isDefault: 1, // 1 预定义 0 自定义
                    isRoot: true,
                    leaf: false, // false 分类 true 数据集
                    // children: res.data.filter((item) => item.isDefault === 1),
                  },
                  {
                    // id: "0",
                    name: "自定义",
                    isDefault: 0,
                    isRoot: true,
                    leaf: false,
                    // children: res.data.filter((item) => item.isDefault === 0),
                    isEnableAdd: true,
                  },
                ],
              },
            ];
            this.typeName = "自定义";
            this.typeId = "0";
            this.getList();
          } else {
            this.groupTreeData = [];
          }
        })
        .finally(() => (this.treeLoading = false));
    },

    getList() {
      // 列表
      this.isLoading = true;
      this.isRequest = true;
      this.query.ruleTypeId = this.currentNodeKey;
      this.query.isDefault = this.query.isDefault;
      fetchRuleList(this.query)
        .then((res) => {
          if (res && res.code === 200) {
            this.ruleList = res.rows.reduce((r, c) => {
              r.push({ ...c, isDisabledForShake: false });
              return r;
            }, []);
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
          }
        })
        .finally(() => {
          this.isLoading = false;
          this.isRequest = false;
        });
    },
    add() {
      //新增按钮
      this.isEdit = false;
      this.isShowAddRule = true;
    },
    handleEdit(row) {
      // 编辑
      if (row && row.status === 0) {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      } else {
        this.isEdit = true;

        ruleDetail({ alertRuleId: row.alertRuleId }).then((res) => {
          if (res && res.code === 200) {
            this.isShowAddRule = true;
            this.editForm = res.data;
          } else {
            this.editForm = {};
          }
        });
      }
    },
    //多选
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.alertRuleId);
      this.selectionRows = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleDelete(row) {
      // 删除
      const ids = row.alertRuleId || this.ids.join(",");

      if (
        (row && row.alertRuleId && row.status === 0) ||
        this.selectionRows.some((item) => item.status === 0)
      ) {
        this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
      } else {
        this.$GlobalDeleteConfirm()
          .then(() => {
            ruleDelete({ ids }).then((res) => {
              if (res && res.code == 200) {
                this.$GlobalSuccessMessage("删除成功");
                if (
                  this.query.pageNum > 1 &&
                  ids.split(",").length === this.list.length
                ) {
                  this.query.pageNum = this.query.pageNum - 1;
                } else {
                  this.query.pageNum = 1;
                }
                this.getList();
              } else {
                this.$GlobalErrorConfirm("删除失败", res.msg).then();
              }
            });
          })
          .catch(() => {});
      }
    },

    handleView(row) {
      // 详情
      ruleDetail({ alertRuleId: row.alertRuleId }).then((res) => {
        if (res && res.code === 200) {
          this.$refs.ruleDetail.show(res.data);
        }
      });
    },

    closeAdd(params) {
      this.isShowAddRule = false;
      if (params) {
        if (params.alertRuleId) {
          let currentRule = this.ruleList.find((item) => {
            return item.alertRuleId === params.alertRuleId;
          });

          currentRule.ruleName = params.ruleName;
          currentRule.ruleCode = params.ruleCode;
          currentRule.ruleType = params.ruleType;
          currentRule.status = params.status;
          currentRule.ruleDetails = params.ruleDetails;
          this.$forceUpdate();
        } else {
          this.getList();
        }
      }
    },

    handleChangeStatus(type) {
      const ids = this.ids.join(",");
      const text = type === 0 ? "启用" : "停用";
      this.$confirm("是否确认" + text + "?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        ruleStatusBatchEdit({ status: type, ids: ids }).then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("操作成功");
            this.getList();
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg).then();
          }
        });
      });
    },

    changeStatus(row) {
      return new Promise((resolve, reject) => {
        ruleEdit({
          status: row.status === 1 ? 0 : 1,
          alertRuleId: row.alertRuleId,
        })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("操作成功");
              resolve(res);
              this.ruleList.find((item) => {
                return item.alertRuleId === row.alertRuleId;
              }).status = row.status === 1 ? 0 : 1;
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg);
              reject();
            }
          })
          .catch(() => reject());
      });
    },
    importShow() {
      //导入
      this.$refs.uploadDialog.show();
    },
    handleExport() {
      //导出
      this.exportLoading = true;
      this.download(
        "datahandler/alertrule/export",
        {
          pageNum: 1,
          pageSize: 10000,
          isDefault: this.query.isDefault,
          ruleTypeId: this.currentNodeKey,
        },
        `ruleTemplate_${new Date().getTime()}.txt`
      ).finally(() => {
        this.exportLoading = false;
      });
    },
    handleQuery() {
      //查询
      this.query.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      // 重置
      this.query = {
        pageNum: 1,
        pageSize: 10,
        ruleCode: null,
        ruleName: null,
        ruleType: null,
        isDefault: this.query.isDefault,
        ruleTypeId: this.currentNodeKey,
      };
    },
  },
};
</script>

<style scoped lang="scss">
.report-component-wrap {
  .tree-item-wrap {
    display: flex;
    align-items: center;
    width: 100%;

    &:hover {
      .iconfont {
        opacity: 1;
      }
    }

    .iconfont {
      opacity: 0;
      transition: opacity 0.15s linear;
    }

    .tree-label {
      margin-right: 4px;
    }

    .pre-icon {
      width: 12px;
      height: 12px;
      font-size: 12px;
    }
  }

  .group-header-wrap {
    height: 32px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group-header-title {
      font-size: 14px;
    }
  }
}
</style>
